from django.shortcuts import render
from django.views.decorators.http import *
from .models import user,member,company
import hashlib as hash
from django.core.mail import send_mail
from django.http import HttpResponse
from time import time
import re
from django.views.generic import View
from django.conf import settings
from django.contrib.auth.hashers import make_password, check_password
from django.template import Context, Template
from django.core.mail import EmailMultiAlternatives
from django.template import Context, loader
from django.http import HttpResponseRedirect
from django.db import connection
from django.utils.translation import ugettext as _
from datetime import *

class reg(View):
	def post(self,request):
		email = request.POST.get('email')
		password = request.POST.get('password')
		repassword = request.POST.get('repassword')
		request.session['error'] = ''
		request.session['emailTip'] = email
		if not re.search('.+@.+\..+',email):
			request.session['error'] = _("This email is not correct.")
		if password != repassword:
			request.session['error'] = _("Twice email were not same.")
		if user.objects.filter(email=email):
			request.session['error'] = _("This email was already.")
		if request.session['error']:
			return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
		password = make_password(password,'kkoffer','pbkdf2_sha256')
		request.session['error'] = ''
		obj = user(email=email,password=password)
		if request.META.get('HTTP_REFERER').find('signIn') > 0:
			obj.type = 2
		else:
			obj.type = 1
		obj.save()
		if obj.type == 2:
			company(uid_id = obj.pk).save()
		# else:
		# 	member(uid_id = obj.pk).save()
		# email = re.search('(.*)@.*',email).group(1)
		request.session['emailName'] = re.search('(.*)@.*',email).group(1)
		request.session['email'] = email
		request.session['id'] = obj.pk
		request.session['type'] = obj.type
		
		return HttpResponseRedirect('/')
	def get(self,request):
		return render(request,'login.html')

class login(View):
	def get(self,request,next):
		return render(request,'login.html')
	def post(self,request,next):
		email = request.POST.get('email')
		password = request.POST.get('password')
		password = make_password(password,'kkoffer','pbkdf2_sha256')
		try:
			obj = user.objects.get(email=email)
		except:
			request.session['error'] = _("This email is not exist.")
			return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
		now = datetime(2016, 10, 25, 19, 48, 49, 728236)
		dt = obj.loginTime
		if dt.replace(tzinfo=None) < now:
			request.session['email'] = obj.email
			# print (obj.loginTime)
			return render(request,'resetPw.html')
		obj = user.objects.filter(email=email).filter(password=password)
		# obj = user.objects.filter(email=email)
		if obj:
			request.session['emailName'] = re.search('(.*)@.*',email).group(1)
			request.session['error'] = ''
			request.session['email'] = email
			request.session['id'] = obj[0].pk
			request.session['type'] = obj[0].type
			request.session['name'] = obj[0].name
			return HttpResponseRedirect('/index')
			# return HttpResponse("成功登录")
		elif user.objects.filter(email=email):
			request.session['error'] = _("This password is not correct.")
			return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
		else:
			request.session['error'] = _("This email is not exist.")
			return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

class findPw(View):
	def get(self,request):
		return render(request,'findPw.html')
	def post(self,request):
		name = request.POST.get('email')
		if not re.search('.+@.+\..+',name):
			request.session['error'] = _("This email format is error")
			return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
		if user.objects.filter(email=name):
			request.session['error'] = ''
			key = make_password(name + settings.SECRET_KEY,'kkoffer','pbkdf2_sha256')
			expire = time() + 60 * 10
			request.session[key] = {'name':name,'expire':expire}
			fromEmail = settings.EMAIL_HOST_USER
			subject,text_content,form_email,to = 'kkoffer找回密码', '<h1>ni hao</h1>', fromEmail,name
			msg = EmailMultiAlternatives(subject,text_content,form_email,[to])
			context = {'key': key,'host':'http://' + request.get_host()}
			# import ipdb; ipdb.set_trace()
			t = loader.get_template('email.html')
			# html_content = t.render(Context(context))
			html_content = t.render(context)
			context = {}
			context['name'] = name
			context['url'] = re.sub(r'(.*)@','http://mail.',name)
			msg.attach_alternative(html_content, 'text/html')
			msg.send()
			return render(request,'send.html',context)
		else:
			request.session['error'] = '没有该邮箱'
			return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

class resetPw(View):
	def get(self,request):
		# return render(request,'email.html',{'key':'cccc'})
		key = request.GET.get('token',None)
		if not key:
			return HttpResponse("参数错误")
		# import ipdb; ipdb.set_trace()
		# key = request.session.get(key)
		# if key.get('exprire') < time():
			# return HttpResponse("已过期")
		# request.session['name'] = key['name']
		return render(request,'resetPw.html')

	def post(self,request):
		pwd = request.POST.get('pwd')
		pwd = make_password(pwd,'kkoffer','pbkdf2_sha256')
		obj = user.objects.get(email=request.session.get('email'))
		obj.password=pwd
		obj.save()
		# del request.session['name']
		return HttpResponseRedirect('/user/login')

class setPw(View):
	def get(self,request):
		return render(request,'setPw.html')

	def post(self,request):
		if not request.session['email']:
			return HttpResponseRedirect('/index')
		email = request.session['email']
		old = request.POST.get('old')
		new = request.POST.get('new')
		if not new:
			return HttpResponse('新密码必须')
		old = make_password(old,'kkoffer','pbkdf2_sha256')
		obj = user.objects.filter(email=email).filter(password=old)
		if obj:
			new = make_password(new,'kkoffer','pbkdf2_sha256')
			user.objects.filter(email=email).update(password=new)
		else:
			request.session['error'] = ''
			return HttpResponse(_('The old password is error'))
		return HttpResponseRedirect('/user/login')


@require_http_methods(["GET"])
def logout(request):
	request.session.clear()
	return HttpResponseRedirect('/index')
















